<template>
  <div>
      <a-card :bordered="false">
      <div class="table-page-search-wrapper">
        <a-form layout="horizontal" >
          <a-row :gutter="8">
            <a-col :md="8" :sm="24">
              <a-form-item label="模型key" :labelCol="labelCol" :wrapperCol="wrapperCol">
                <a-input v-model="queryParam.modelKey" placeholder="流程模型key"/>
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="模型名称" :labelCol="labelCol" :wrapperCol="wrapperCol">
                <a-input v-model="queryParam.name" placeholder="模糊查询流程模型名称"/>
              </a-form-item>
            </a-col>
            <template v-if="advanced">
              <a-col :md="8" :sm="24">
                <a-form-item label="引擎类型" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-select v-model="queryParam.modelType" placeholder="请选择" allowClear default-value="1">
                    <a-select-option value="0">BPMN</a-select-option>
                    <a-select-option value="2">FORM</a-select-option>
                    <a-select-option value="3">APP</a-select-option>
                    <a-select-option value="4">DECISION_TABLE</a-select-option>
                    <a-select-option value="5">CMMN</a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
            </template>
            <a-col :md="!advanced && 8 || 24" :sm="24">
              <span class="table-page-search-submitButtons" :style="advanced && { float: 'right', overflow: 'hidden' } || {} ">
                <a-button type="primary" @click="() =>{this.findModelListBtn()}">查询</a-button>
                <a-button style="margin-left: 8px" @click="() => {this.clearQueryAll()}">重置</a-button>
                <a @click="toggleAdvanced" style="margin-left: 8px">
                  {{ advanced ? '收起' : '展开' }}
                  <a-icon :type="advanced ? 'up' : 'down'"/>
                </a>
              </span>
            </a-col>
          </a-row>
        </a-form>
      </div>
     
      <vxe-grid
        class="vxe-table-antd"
        resizable
        show-overflow
        ref="modelListTable"
        stripe
        border
        highlight-hover-row
        highlight-current-row
        highlight-hover-column
        highlight-current-column
        highlight-cell
        row-id="id"
        height="400"
        size="small"
        :columns="tableColumn"
        :data="tableData"
        :loading="loading"
        :start-index="(tablePage.currentPage - 1) * tablePage.pageSize"
        :pager-config="tablePage"
        @page-change="handlePageChange">
        <!--自定义插槽 toolbar 插槽-->
        <template v-slot:toolbar>
            <vxe-toolbar custom zoom >
              <template v-slot:buttons>
                <a-button   @click="addBtn"  type="primary">新增</a-button>
              </template>
            </vxe-toolbar>
        </template>
        <template v-slot:version_default="{ row }">
          <a-tooltip placement="top">
            <template slot="title">
              <span>查看历史流程信息</span>
            </template>
            <span style="color:blue;cursor: pointer;" @click="showHistoryDrawer(row)">V:{{row.version}}</span>
          </a-tooltip>
        </template>
        <template v-slot:xml_default="{ row }">
            <span style="color:blue;cursor: pointer;" @click="showXmlDrawer(row.id)">{{row.name}}.bpmn20.xml</span>
        </template>
        <template v-slot:thumbnail_default="{ row }">
            <span style="color:blue;cursor: pointer;" @click="showImgDrawer(row.id)">{{row.name}}.png</span>
        </template>
        <template v-slot:edit_default="{ row }">
            <a-tooltip placement="top">
                <template slot="title">
                <span>修改模型信息</span>
                </template>
            <a-icon style="padding-right:10px;color: #00BFFF;cursor: pointer;" theme="filled"  type="edit" @click="editBtn(row)"></a-icon>
            </a-tooltip>
            <a-tooltip placement="top">
                <template slot="title">
                <span>复制模型信息</span>
                </template>
            <a-icon style="padding-right:10px;color: #800080;cursor: pointer;" type="copy" @click="copyBtn(row)"></a-icon>
            </a-tooltip>
            <a-tooltip placement="top">
                <template slot="title">
                <span>设计流程图</span>
                </template>
            <a-icon style="padding-right:10px;color: #3CB371;cursor: pointer;"  type="form" @click="showDrawer(row.id)" ></a-icon>
            </a-tooltip>
            <a-tooltip placement="top">
                <template slot="title">
                <span>部署流程</span>
                </template>
            <a-icon style="padding-right:10px;color: #00FF00;cursor: pointer;"  type="thunderbolt" @click="deployBtn(row)" ></a-icon>
            </a-tooltip>
            <a-tooltip placement="top">
                <template slot="title">
                <span>下载流程文件</span>
                </template>
            <a-icon style="padding-right:10px;color: #0000FF;cursor: pointer;"  type="download" @click="downloadXmlBtn(row)" ></a-icon>
            </a-tooltip>
            <a-tooltip placement="top">
                <template slot="title">
                <span>上传流程文件</span>
                </template>
            <a-icon style="padding-right:10px;color: #FFA500;cursor: pointer;"  type="upload"  @click="uploadXmlBtn(row)" ></a-icon>
            </a-tooltip>
            <a-tooltip placement="top">
                <template slot="title">
                <span>删除流程模型</span>
                </template>
                <a-popconfirm
                  placement="left"
                  title="是否确定删除该模型?"
                  ok-text="确定"
                  cancel-text="取消"
                  @confirm="delConfirm(row.id)"
                >
                <a-icon style="padding-right:10px;color: #FF0000;cursor: pointer;" theme="filled" type="delete" ></a-icon>
                </a-popconfirm>
            </a-tooltip>
        </template>
      </vxe-grid>
    </a-card>
    <a-modal
        :title="modalTitle"
        centered
        style="top: 10px;"
        width="50%"
        destroyOnClose
        v-model="modelVisible"
        @ok="saveModel"
        cancelText="关闭"
        okText="保存"
    >
        <a-form-model ref="modelPage" :model="modelForm" :rules="rules" :label-col="modelLabelCol" :wrapper-col="modelWrapperCol">
          <a-form-model-item label="模型Key">
            <a-input v-model="modelForm.modelKey" />
          </a-form-model-item>
          <a-form-model-item label="模型名称">
            <a-input v-model="modelForm.name" />
          </a-form-model-item>
          <a-form-model-item label="模型描述">
            <a-textarea :rows="5" v-model="modelForm.description" />
          </a-form-model-item>
        </a-form-model>
    </a-modal>
    <a-modal
        title="部署流程"
        centered
        style="top: 10px;"
        width="600px"
        destroyOnClose
        v-model="modelDeployVisible"
        @ok="saveDeploy"
        cancelText="关闭"
        okText="保存"
    >
      <a-form-model ref="modelDeployPage" :model="deployForm" :rules="deployRules" :label-col="modelLabelCol" :wrapper-col="modelWrapperCol">
        <a-form-model-item label="模型名称">
          <a-input v-model="deployForm.name" :disabled="true"/>
        </a-form-model-item>
        <a-form-model-item label="业务类型" >
          <a-select
            placeholder="请选择"
            allowClear
            v-model="deployForm.operationType"
            @change="operationTypeChange"
          >
            <a-select-option v-for="item in dictData.operationType" :key="item.dictKey" :value="item.dictKey">{{ item.dictValue }}</a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item label="模型id" :style="{display:'none'}">
          <a-input v-model="deployForm.id" />
        </a-form-model-item>
        <a-form-model-item label="业务类型名称" :style="{display:'none'}">
          <a-input v-model="deployForm.operationName" />
        </a-form-model-item>
      </a-form-model>
    </a-modal>
    <a-modal
        title="文件上传"
        centered
        style="top: 10px;"
        width="500px"
        destroyOnClose
        v-model="modelImpVisible"
        :ok-button-props="{ props: { disabled: fileList.length === 0 } }"
        @ok="uploadXml"
        cancelText="关闭"
        :okText="uploading?'上传中...':'上传'"
    >
    <a-upload :file-list="fileList" :remove="handleRemove" :before-upload="beforeUpload">
      <a-button> <a-icon type="upload" /> 选择文件</a-button>
    </a-upload>
    </a-modal>
    <a-drawer
        placement="right"
        :closable="true"
        :destroyOnClose="true"
        width="95%"
        :visible="eidtVisible"
        @close="onClose"
    >
        <iframe 
            height="600px"
                width="100%"
                scrolling="no"
                id="iframeEditId"
                :src="modelEditorUrl"
                frameborder="0">
        </iframe>
    </a-drawer>
    <a-drawer
        placement="right"
        :closable="true"
        :destroyOnClose="true"
        width="85%"
        :visible="imgVisible"
        @close="onImgClose"
    >
        <img :src="imgSrc" />
    </a-drawer>
    <a-drawer
        placement="right"
        :closable="true"
        :destroyOnClose="true"
        width="85%"
        :visible="xmlVisible"
        @close="onXmlClose"
    >
      <pre v-highlight>
        <code >{{xmlValue}}</code>
      </pre>
    </a-drawer>
    <a-drawer
        placement="left"
        :closable="true"
        :destroyOnClose="true"
        width="60%"
        :visible="historyVisible"
        @close="onHistoryClose"
    >
      <a-descriptions title="流程模型信息">
        <a-descriptions-item label="流程模型key">
          {{modelData.modelKey}}
        </a-descriptions-item>
        <a-descriptions-item label="流程模型名称">
          {{modelData.name}}
        </a-descriptions-item>
      </a-descriptions>
      <vxe-grid
        class="vxe-table-antd"
        resizable
        show-overflow
        ref="modelListTable"
        stripe
        border
        highlight-hover-row
        highlight-current-row
        highlight-hover-column
        highlight-current-column
        highlight-cell
        row-id="id"
        height="400"
        size="small"
        :columns="tableHistoryColumn"
        :data="tableHistoryData"
        :loading="loadingHistory">
        <template v-slot:xml_download_default="{ row }">
            <span style="color:blue;cursor: pointer;" @click="downloadHistoryXmlBtn(row)">{{row.name}}.bpmn20.xml</span>
        </template>
        <template v-slot:version_history_default="{ row }">
          <span >V:{{row.version}}</span>
        </template>
      </vxe-grid>
    </a-drawer>
  </div>
</template>
<script>
import { getModelList,addModel,editModel,copyModel,delModel,getModelEditorPage,getImage,getXml,getHistoryListById,downloadHistoryXml,downloadXml,deploy,uploadXmlFile } from "@/services/system/workflowApi.js"
import { getBatchDict } from "@/services/system/api"
import modal from 'ant-design-vue/es/modal'
import vkbeautify from 'vkbeautify'
export default {
  name: 'ModelList',
  components: {
  },
  data () {
    return {
      description: '流程模型管理',
      modalTitle:'操作',
      modelVisible:false,
      modelForm:{modelKey:'',id:'',name:'',description:''},
      rules:{
        modelKey: [{ required: true, message: '模型key不能为空', trigger: 'blur' }],
        name: [{ required: true, message: '模型名称不能为空', trigger: 'blur' }]
      },
      modelDeployVisible:false,
      deployForm:{operationType:'',id:'',name:'',operationName:''},
      deployRules:{
        operationType: [{ required: true, message: '业务类型不能为空', trigger: 'blur' }]
      },
      dictData: {},
      saveType:"add",
      labelCol: {
        xs: { span: 24 },
        sm: { span: 6 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 18 }
      },
      modelLabelCol: {
        xs: { span: 24 },
        sm: { span: 3 }
      },
      modelWrapperCol: {
        xs: { span: 24 },
        sm: { span: 21 }
      },
      // 高级搜索 展开/关闭
      advanced: false,
      // 查询参数
      queryParam: {},
       // 表头
      loading: false,
      tablePage: {
        total: 0,
        currentPage: 1,
        pageNum: 1,
        pageSize: 20
      },
      tableColumn: [
        { type: 'seq', width: 60, fixed: 'left', align: 'center', title: '序号' },
        { field: 'id', title: '模型id', fixed: 'left', visible: false, align: 'center', width: 150 },
        { field: 'name', title: '流程模型名称', align: 'center', fixed: 'left', width: 200 },
        { field: 'modelKey', title: '流程模型key', align: 'center',  width: 120 },
        { field: 'version', title: '版本号',slots: {default: 'version_default'}, align: 'center',  width: 80 },
        { field: 'modelType', title: '流程引擎类型', visible: false, align: 'center',  width: 80 },
        { field: 'modelTypeName', title: '流程引擎类型', align: 'center',  width: 150 },
        { field: 'description', title: '描述', align: 'center', showOverflow: true,width: 200 },
        { field: 'modelEditorJson', title: '模型XML',slots: {default: 'xml_default'}, align: 'center',  width: 150 },
        { field: 'thumbnail', title: '流程图',slots: {default: 'thumbnail_default'}, align: 'center',  width: 150 },
        { field: 'created', title: '创建时间', align: 'center', width: 200 },
        { field: 'createdBy', title: '创建人', align: 'center', width: 150 },
        { field: 'lastUpdated', title: '修改时间', align: 'center', width: 200 },
        { field: 'lastUpdatedBy', title: '修改人', align: 'center', width: 150 },
        { field: 'tenantId', title: '租户id', align: 'center', width: 150 },
        { field: 'modelComment', title: '备注', align: 'center', showOverflow: true, width: 350 },
        { field: 'edit', title: '操作', align: 'center',  width: 200,fixed: 'right',slots: {default: 'edit_default'} }
      ],
      tableData: [],
      eidtVisible:false,
      modelEditorUrl:'',
      imgVisible:false,
      imgSrc:'',
      xmlVisible:false,
      xmlValue:'',
      modelData:{},
      historyVisible:false,
      loadingHistory:false,
      tableHistoryColumn: [
        { type: 'seq', width: 60,  align: 'center', title: '序号' },
        { field: 'id', title: '历史模型id',  visible: false, align: 'center', width: 150 },
        { field: 'name', title: '流程模型名称',  visible: false, align: 'center', fixed: 'left', width: 250 },
        { field: 'modelKey', title: '流程模型key',  visible: false, align: 'center',  width: 120 },
        { field: 'version', title: '版本号',slots: {default: 'version_history_default'}, align: 'center',  width: 80 },
        { field: 'modelType', title: '流程引擎类型', visible: false, align: 'center',  width: 80 },
        { field: 'modelTypeName', title: '流程引擎类型', align: 'center',  width: 150 },
        { field: 'description', title: '描述',  visible: false, align: 'center', showOverflow: true,width: 200 },
        { field: 'modelEditorJson', title: '模型XML',slots: {default: 'xml_download_default'}, align: 'center',  width: 150 },
        { field: 'modelId', title: '模型id',  visible: false, align: 'center', width: 100 },
        { field: 'removalDate', title: '移动时间', align: 'center', width: 200 },
        { field: 'created', title: '创建时间',  visible: false, align: 'center', width: 100 },
        { field: 'createdBy', title: '创建人',  visible: false, align: 'center', width: 150 },
        { field: 'lastUpdated', title: '修改时间',  visible: false, align: 'center', width: 100 },
        { field: 'lastUpdatedBy', title: '修改人',  visible: false, align: 'center', width: 150 },
        { field: 'tenantId',  visible: false, title: '租户id', align: 'center', width: 150 },
        { field: 'modelComment',  visible: false, title: '备注', align: 'center', showOverflow: true, width: 350 },
      ],
      tableHistoryData: [],
      fileList:[],
      uploading: false,
      modelImpVisible:false,
    }
  },
  mounted(){
   
  },
  created () {
    // 初始化模型列表
    this.findModelList()
     // 数据初始化
    const params = {}
    params.dictFields = 'operationType'
    this.$http.post(getBatchDict,params).then(res => {
      this.dictData = res.result
    })
  },
  methods: {
    toggleAdvanced () {
      this.advanced = !this.advanced
    },
    handlePageChange ({ currentPage, pageSize }) {
      this.tablePage.pageNum = currentPage
      this.tablePage.currentPage = currentPage
      this.tablePage.pageSize = pageSize
      this.findModelList()
    },
    findModelListBtn () {
      this.tablePage.pageNum = 1
      this.tablePage.currentPage = 1
      this.findModelList()
    },
     // 模型列表查询
    findModelList () {
      this.loading = true
      const params = Object.assign(this.queryParam, this.tablePage)
      setTimeout(() => {
        this.$http.post(getModelList,params).then((res) => {
          const data = res.result.list
          this.tableData = data
          this.tablePage.total = res.result.total
          this.tablePage.pageNum = res.result.pageNum
          this.tablePage.currentPage = res.result.pageNum
          this.tablePage.pageSize = res.result.pageSize
          this.loading = false
        }).catch(() => {
          this.loading = false
        })
      }, 200)
    },
    addBtn(){
      this.modalTitle = '新增模型'
      this.modelVisible = true
      this.saveType = 'add'
      this.modelForm={modelKey:'',id:'',name:'',description:''}
    },
    editBtn(row){
      this.modalTitle = '修改模型'
      this.modelVisible = true
      this.saveType = 'edit'
      this.modelForm={...row}
    },
    copyBtn(row){
      this.modalTitle = '复制模型'
      this.modelVisible = true
      this.saveType = 'copy'
      this.modelForm={...row}
    },
    delConfirm(id){
      setTimeout(() => {
        const params = {}
        params.id = id
        this.$http.post(delModel,params).then(() => {
           modal.info({ title: '成功提示', content: '删除模型成功' })
           this.findModelList()
        }).catch(() => {
          
        })
      }, 200)
    },
    saveModel(){
      this.$refs.modelPage.validate(valid => {
        if (valid) {
          const params = {...this.modelForm}
          if (this.saveType=='add') {
            this.$http.post(addModel,params).then((res) => {
                const id = res.result.id
                this.modelVisible=false
                this.findModelList()
                this.showDrawer(id)
            }).catch(() => {
                
            })
          }else if (this.saveType=='edit') {
            this.$http.post(editModel,params).then((res) => {
                modal.info({ title: '成功提示', content: '修改成功' })
                let data = [...this.tableData]
                data.forEach((item, index, arr) => {
                  if (item.id === res.result.id) {
                    arr.splice(index, 1, res.result)
                    return item
                  }
                })
                this.tableData = data
                this.modelVisible=false
            }).catch(() => {
                
            })
          }else if (this.saveType=='copy') {
            this.$http.post(copyModel,params).then(() => {
                modal.info({ title: '成功提示', content: '复制成功' })
                this.modelVisible=false
                this.findModelList()
            }).catch(() => {
                
            })
          }
          
        } else {
          console.log('error submit!!');
          return false;
        }
      })
    },
    clearQueryAll () {
      this.queryParam = {}
      this.findModelList()
    },
    showDrawer(id) {
      this.modelEditorUrl = getModelEditorPage+id+'?time=' + new Date().getTime()
      this.eidtVisible = true
    },
    onClose() {
      this.eidtVisible = false
      this.findModelList()
    },
    showImgDrawer(id) {
      const params ={}
      params.id=id
      this.$http.post(getImage,params).then((res) => {
        this.imgSrc = res.result
        this.imgVisible = true
      }).catch(() => {
                
      })      
    },
    onImgClose(){
      this.imgVisible = false
    },
    showXmlDrawer(id) {
      const params ={}
      params.id=id
      this.$http.post(getXml,params).then((res) => {
        this.xmlValue = vkbeautify.xml(res.result)
        this.xmlVisible = true
      }).catch(() => {
                
      })
    },
    onXmlClose(){
      this.xmlVisible = false
    },
    showHistoryDrawer(row) {
      this.modelData = row
      const params ={}
      params.id=row.id
      this.$http.post(getHistoryListById,params).then((res) => {
        this.tableHistoryData = res.result
        this.historyVisible = true
      }).catch(() => {
                
      })
    },
    onHistoryClose(){
      this.historyVisible = false
    },
    downloadXmlBtn(row){
      let url =downloadXml+'?time=' + new Date().getTime()
      url=url.replace('{processModelId}',row.id)
      let fileName =row.name+'.bpmn20.xml'
      this.$http.downloadFile(url,fileName,{})
    },
    downloadHistoryXmlBtn(row){
      let url =downloadHistoryXml+'?time=' + new Date().getTime()
      url=url.replace('{processModelId}',row.modelId).replace('{processModelHistoryId}',row.id)
      let fileName =row.name+'.bpmn20.xml'
      this.$http.downloadFile(url,fileName,{})
    },
    deployBtn(row){
      this.modelDeployVisible=true
      this.deployForm={...row}
    },
    saveDeploy(){
      this.$refs.modelDeployPage.validate(valid => {
        if (valid) {
          const params = {...this.deployForm}
            this.$http.post(deploy,params).then(() => {
              this.modelDeployVisible=false
              modal.info({ title: '成功提示', content: '部署成功' })
            }).catch(() => {
                
            })
        } else {
          console.log('error submit!!');
          return false;
        }
      })
    },
    operationTypeChange (value) {
      let data = [...this.dictData.operationType]
      let dictValue = ''
      data.forEach((item) => {
        if (item.dictKey === value) {
          dictValue=item.dictValue
          return
        }
      })
      let deployForm ={...this.deployForm}
      deployForm.operationName=dictValue
      this.deployForm=deployForm
      console.log(deployForm)
    },
    uploadXmlBtn(row){
      this.modelData = row
      this.modelImpVisible = true
    },
    uploadXml(){
      const { fileList } = this;
      const formData = new FormData();
      formData.append('file', fileList[0]);
      formData.append('id', this.modelData.id);
      this.uploading=true
      this.$http.uploadAction(uploadXmlFile,formData).then(() => {
        this.modelImpVisible=false
        modal.info({ title: '成功提示', content: '上传成功' })
      }).catch(() => {
        this.uploading=false
      })
    },
    handleRemove(file) {
      const index = this.fileList.indexOf(file);
      const newFileList = this.fileList.slice();
      newFileList.splice(index, 1);
      this.fileList = newFileList;
    },
    beforeUpload(file) {
      this.fileList = [ file];
      return false;
    },
  }
}
</script>
<style lang="less" scoped>
</style>